import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import {
  Router,
  Route,
  IndexRoute,
  Redirect,
  browserHistory,
} from 'react-router';
import { AppContainer } from 'react-hot-loader';
import configureStore from './stores';
import * as Cookies from 'js-cookie';
import Pages from './containers/Pages';
import * as Definitions from './containers/Definitions';


const [store, storeHistory] = configureStore(browserHistory);

const requireAuth = store => (nextState, replace) => {
  if (!store.getState().My.Session.hasLoggedIn && !Cookies.get(Definitions.ACCESS_TOKEN_KEY)) {
    replace(`/login?returnUrl=${nextState.location.pathname}`);
  }
};

const bootstrap = () => {
  ReactDOM.render(
    <AppContainer>
      <Provider store={store}>
        <Router onUpdate={() => window.scrollTo(0, 0)} history={storeHistory}>
          <Route path="/" component={Pages.RootComponent}>
            <IndexRoute component={Pages.HomeComponent} />
            <Route path="my" component={Pages.MyComponent} onEnter={requireAuth(store)}>
              <Route path="uploads" component={Pages.UploadsComponent} />
              <Route path="published" component={Pages.PublishedComponent} />
              <Route path="likes" component={Pages.LikesComponent} />
            </Route>
            <Route path="user/:id" component={Pages.UserComponent} />
            <Route path="work/:workId/detail" component={Pages.WorkDetailComponent} />
            <Route path="work/:workId/detail/mine" component={Pages.MyWorkDetailComponent} onEnter={requireAuth(store)} />
            <Route path="work/:workId/detail/embed" component={Pages.EmbedWorkDetailComponent} />
            <Route path="work/:workId/edit" component={Pages.WorkEditComponent} onEnter={requireAuth(store)} />
            <Route path="works/all/featured" component={Pages.RecommendedWorksComponent} />
            <Route path="works/all/latest" component={Pages.LatestWorksComponent} />
            <Route path="works/category/:id" component={Pages.CategoryWorksComponent} />
            <Route path="login" components={Pages.LoginContainer} />
            <Redirect from="*" to="/" />
          </Route>
        </Router>
      </Provider>
    </AppContainer>,
    document.getElementById('root'),
  );
};

export default bootstrap;

